package com.daichi.yygh.order.controller;

import com.daichi.yygh.common.result.Result;
import com.daichi.yygh.order.service.PaymentService;
import com.daichi.yygh.order.service.WeixinService;
import com.github.wxpay.sdk.WXPayConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Api("微信支付")
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    private final WeixinService weixinService;

    private final PaymentService paymentService;

    @Autowired
    public WeixinController(WeixinService weixinService, PaymentService paymentService) {
        this.weixinService = weixinService;
        this.paymentService = paymentService;
    }

    @ApiOperation(value = "生成微信二维码")
    @GetMapping("createNative/{orderId}")
    public Result createNative(@PathVariable Long orderId) {
        Map<String, Object> map = weixinService.createNative(orderId);
        return Result.ok(map);
    }

    @ApiOperation(value = "查询支付状态")
    @GetMapping("queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable Long orderId) {
        Map<String, String> map = weixinService.queryPayStatus(orderId);
        if (map == null) {
            return Result.fail().message("支付出错");
        }
        if (WXPayConstants.SUCCESS.equals(map.get("trade_state"))) {
            String outTradeNo = map.get("out_trade_no");
            paymentService.paySuccess(outTradeNo, map);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }
}
